<template>
  <div class="detail">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-position="right"
      label-width="110px"
    >
      <div class="form-data">
        <el-form-item label="用户名" prop="user_name">
          <el-input
            v-model="postForm.user_name"
            placeholder="用户名"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="所属权限组" prop="role_id">
          <el-select
            v-model.number="postForm.role_id"
            placeholder="用户组"
            style="width: 100%"
          >
            <el-option v-for="item in rolesOptions" :key="item.id" :value="item.id" :label="item.title + '(' + item.name + ')'" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户别名" prop="nick_name">
          <el-input
            v-model="postForm.nick_name"
            placeholder="用户别名"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item ref="postForm_password" label="密码" prop="password">
          <el-input
            v-model="postForm.password"
            type="password"
            placeholder="密码"
            style="width: 100%"
            @input="handlePasswordInput"
          />
        </el-form-item>
        <el-form-item ref="postForm_checkpass" label="再次输入密码" prop="checkpass">
          <el-input
            v-model="postForm.checkpass"
            type="password"
            placeholder="再次输入密码"
            style="width: 100%"
            :disabled="!postForm.password || postForm.password === '' ? true : false"
          />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <!-- <el-input
            v-model="postForm.avatar"
            placeholder="头像"
            style="width: 100%"
          /> -->
          <image-item
            ref="imageItem"
            v-model="postForm.avatar"
            placeholder="头像"
            style="width: 100%"
            :limit="1"
            save-dir-name="admin_avatar"
          />
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input
            v-model="postForm.introduction"
            type="textarea"
            autosize
            placeholder="简介"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model.number="postForm.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model.number="postForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </div>

      <sticky :class-name="'sub-navbar'">
        <el-button
          v-loading="loading"
          type="success"
          style="margin-left: 10px"
          @click="submitForm"
        >
          {{ isEdit ? '编辑' : '添加' }}
        </el-button>
      </sticky>
    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import TnUploadImageItem from '@/components/TNUploadImageItem'
import { getAllAuthRole } from '@/api/auth-role'
import { getAdminByID, addAdmin, editAdmin } from '@/api/admin'
import crypto from 'crypto'

const validateUserName = (rule, value, callback) => {
  if (!(/^\w{3,20}$/.test(value))) {
    const errMsg = '用户名只能包含英文字母、数字、_、-'
    // this.showMessage(errMsg, 'error')
    callback(new Error(errMsg))
  } else {
    callback()
  }
}
const validateNickName = (rule, value, callback) => {
  if (!(/^[\u4E00-\u9FA5A-Za-z0-9_]{3,20}$/.test(value))) {
    const errMsg = '用户别名只能包含汉字、英文、数字、下划线'
    // this.showMessage(errMsg, 'error')
    callback(new Error(errMsg))
  } else {
    callback()
  }
}

export default {
  name: 'AdminDetail',
  components: { Sticky, 'image-item': TnUploadImageItem },
  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      isEdit: false,
      loading: false,
      rolesOptions: [],
      postForm: {
        user_name: '',
        password: '',
        checkpass: '',
        avatar: '',
        nick_name: '',
        introduction: '',
        role_id: '',
        gender: 0,
        status: 1
      },
      rules: {
        user_name: [
          { required: true, message: '用户名不能为空' },
          { validator: validateUserName, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空' },
          { validator: this.validatePassword, trigger: 'change' }
        ],
        checkpass: [
          { required: true, message: '再次输入的密码不能为空' },
          { validator: this.validateCheckPass, trigger: 'change' }
        ],
        avatar: [{ max: 255, message: '头像地址最大长度不能超过255', trigger: 'blur' }],
        nick_name: [
          { required: true, message: '别名不能为空' },
          { validator: validateNickName, trigger: 'blur' }
        ],
        introduction: [{ max: 255, message: '简介最大长度不能超过255', trigger: 'blur' }],
        role_id: [{ required: true, message: '所属权限组不能为空' }],
        gender: [
          { required: true, message: '性别不能为空' },
          { type: 'number', message: '性别值格式不正确' }
        ],
        status: [
          { required: true, message: '状态不能为空' },
          { type: 'number', message: '状态值格式不正确' }
        ]
      }
    }
  },
  // watch: {
  //   id(val) {
  //     this.id = val
  //     this.getAdminByID()
  //   }
  // },
  // created() {
  //   getAllAuthRole().then(response => {
  //     const { data } = response
  //     this.rolesOptions = data
  //     this.getAdminByID()
  //   })
  // },
  methods: {
    submitForm() {
      if (!this.loading) {
        this.loading = true
        this.$refs.postForm.validate((valid, fields) => {
          // console.log(valid, fields)

          // 判断规则是否验证通过
          if (valid) {
            const admin = Object.assign({}, this.postForm)

            if (admin.password &&
              admin.password !== '' &&
              admin.checkpass &&
              admin.checkpass !== '') {
            // 对密码进行md5加密后再进行传输
              let md5 = crypto.createHash('md5')
              md5.update(admin.password)
              admin.password = md5.digest('hex')

              md5 = crypto.createHash('md5')
              md5.update(admin.checkpass)
              admin.checkpass = md5.digest('hex')
            }
            // console.log(admin)

            if (!this.isEdit) {
              addAdmin(admin).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            } else {
              admin.id = this.id
              editAdmin(admin).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
                this.toDefault()
              })
            }
          } else {
            this.loading = false
            for (const key in fields) {
              if (fields.hasOwnProperty(key)) {
                const element = fields[key]
                this.$message({
                  message: element[0].message,
                  type: 'error',
                  duration: 2000
                })
                return false
              }
            }
          }
        })
      }
    },
    handlePasswordInput(value) {
      if (!this.isEdit) {
        return
      }
      if (value || value.length > 0) {
        this._addPasswordRules()
      } else {
        this._removePasswordRules()
      }
    },
    getAdminByID() {
      if (this.id !== 0) {
        getAdminByID(this.id).then(response => {
          if (!response.data || response.data.length === 0) {
            this.isEdit = false
            return
          }

          const {
            user_name,
            nick_name,
            avatar,
            gender,
            role_id,
            introduction,
            status
          } = response.data
          this.postForm = {
            user_name,
            nick_name,
            gender,
            role_id,
            introduction,
            status
          }
          this.postForm.avatar = avatar.value
          this.isEdit = true
          this._removePasswordRules()
        })
      } else {
        this.isEdit = false
      }
    },
    toDefault() {
      this.$refs.postForm.resetFields()
      this.uploadImageList = []
      this.loading = false
    },
    getAllAuthRole() {
      getAllAuthRole().then(response => {
        const { data } = response
        this.rolesOptions = data
        this.getAdminByID()
      })
    },
    _addPasswordRules() {
      this.rules.password = [
        { required: true, message: '密码不能为空' },
        { validator: this.validatePassword, trigger: 'change' }
      ]
      this.rules.checkpass = [
        { required: true, message: '再次输入的密码不能为空' },
        { validator: this.validateCheckPass, trigger: 'change' }
      ]
    },
    _removePasswordRules() {
      this.rules.password = []
      this.rules.checkpass = []
      this.$refs.postForm_password.clearValidate()
      this.$refs.postForm_checkpass.clearValidate()
    },
    validatePassword(rule, value, callback) {
      if (!(/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,20}$/.test(value))) {
        const errMsg = '密码必须包含数字和字母，长度为6到20位'
        callback(new Error(errMsg))
      } else {
        if (this.$refs.postForm.checkpass !== '') {
          this.$refs.postForm.validateField('checkpass')
        }
        callback()
      }
    },
    validateCheckPass(rule, value, callback) {
      let errMsg = ''
      if (!value || value === '') {
        errMsg = '请再次输入密码'
        callback(new Error(errMsg))
      } else if (this.postForm.password !== value) {
        errMsg = '两次输入的密码不一致'
        callback(new Error(errMsg))
      } else {
        callback()
      }
    }
  }
}
</script>

<style lang="scss">
.form-data {
  margin-top: 10px;
}
</style>
